/**
 * 
 */
package com.tianqi.rms.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.MediaApi;
import com.jfinal.weixin.sdk.api.MediaFile;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.tianqi.rms.model.WeixinUser;
import com.tianqi.rms.model.business.Shop;
import com.tianqi.rms.model.business.TimeCard;
import com.tianqi.rms.model.business.ValueCard;
import com.tianqi.rms.model.business.Vip;
import com.tianqi.rms.util.OauthUtils;
import com.tianqi.rms.util.ShakeUtils;
import com.tianqi.tools.IdGenerateTool;

/**
 *
 *                #####################################################
 *                #                                                   #
 *                #                       _oo0oo_                     #
 *                #                      o8888888o                    #
 *                #                      88" . "88                    #
 *                #                      (| -_- |)                    #
 *                #                      0\  =  /0                    #
 *                #                    ___/`---'\___                  #
 *                #                  .' \\|     |# '.                 #
 *                #                 / \\|||  :  |||# \                #
 *                #                / _||||| -:- |||||- \              #
 *                #               |   | \\\  -  #/ |   |              #
 *                #               | \_|  ''\---/''  |_/ |             #
 *                #               \  .-\__  '-'  ___/-. /             #
 *                #             ___'. .'  /--.--\  `. .'___           #
 *                #          ."" '<  `.___\_<|>_/___.' >' "".         #
 *                #         | | :  `- \`.;`\ _ /`;.`/ - ` : | |       #
 *                #         \  \ `_.   \_ __\ /__ _/   .-` /  /       #
 *                #     =====`-.____`.___ \_____/___.-`___.-'=====    #
 *                #                       `=---='                     #
 *                #     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   #
 *                #                                                   #
 *                #               佛祖保佑         永无BUG              #
 *                #                        						      #
 *                #####################################################
 *								yanglong : Dec 10, 2018 8:45:44 PM 尊上
 *										Vip个人中心
 */
public class UserController extends Controller {

	String base_url = PropKit.use("a_little_config.txt").get("baseUrl")+"vipCentent/";
	/**
	 *******************************************
	 * 方法名称:入口
	 * 创建人：yanglong
	 * 创建时间：2018年4月17日 下午11:44:27
	 * 参数type:
	 * ******** toVipCentent 到会员中心页面
	 * ******** toUserCar 到会员卡券页面
	 * @return:void
	 *******************************************
	 */
	public void oauth() {
		String type=getPara("type");
		String redirect_uri="";
		switch (type) {
		case "toVipCentent":
			redirect_uri=base_url+"toVipCentent";
			break;
		case "toUserCar":
			redirect_uri=base_url+"toUserCar";
			break;
		default:
			redirect_uri=base_url+"toVipCentent";
			break;
		}
		String return_url = OauthUtils.publicOauth(redirect_uri);
		redirect(return_url);
	}
	/**
	 *******************************************
	 * 项目名称:weixin_meifa
	 * 方法名称:
	 * 创建人：yanglong
	 * 创建时间：Dec 10, 2018 8:47:07 PM   
	 * @version
	 *******************************************
	 */
	public void toVipCentent() {
		String code = getPara("code");
		if(code != null){
			ApiConfig ac = ApiConfigKit.getApiConfig();
			ApiConfigKit.putApiConfig(ac);
			ApiConfigKit.setThreadLocalAppId(ac.getAppId());
			String appId = ac.getAppId();
			String secret = ac.getAppSecret();
			SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(appId, secret, code);
			Integer errorCode=snsAccessToken.getErrorCode();
			if(errorCode!=null) {
				redirect("/vipCentent/oauth?type=toVipCentent");
				return;
			}
			String openId = snsAccessToken.getOpenid();
			try {
				WeixinUser wxUser = WeixinUser.dao.getUserByOpenId(openId);
				//用户直接进没有注册
				if(wxUser==null || StringUtils.isEmpty(wxUser.getTel())) {
					redirect("/enroll/oauth");
					return;
				}
				//用户没有记录会员信息
				else if(wxUser.getVipId()==null) {
					redirect("/vipCentent/tocreateUser?openId="+openId);
					return;
				}else {
					Vip vip = Vip.dao.findById(wxUser.getVipId());
					setAttr("vip", vip);
				}
				setAttr("wxUser", wxUser);
				setAttr("pagetype", "vipCenente");
				render("vipCentent.jsp");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 *******************************************
	 * 项目名称:weixin_meifa   
	 * 方法名称:
	 * 创建人：yanglong
	 * 创建时间：Dec 12, 2018 7:34:09 PM   
	 * @version
	 *******************************************
	 */
	public void vipCentent() {
		WeixinUser wxUser = WeixinUser.dao.getUserByOpenId("ovkND1itmmP-OgjLY99R-i7c7nsM");
		setAttr("wxUser", wxUser);
		Vip vip = Vip.dao.findById(wxUser.getVipId());
		setAttr("vip", vip);
		// TODO Auto-generated method stub
		render("vipCentent.jsp");
	}



	/**
	 *******************************************
	 * 项目名称:weixin_meifa   
	 * 方法名称:
	 * 创建人：yanglong
	 * 创建时间：Dec 12, 2018 7:40:40 PM   
	 * @version
	 *******************************************
	 */
	int shop_id = Integer.parseInt(PropKit.use("a_little_config.txt").get("shop_id"));

	public void toUserCar() {
		String code = getPara("code");
		if(code != null){
			ApiConfig ac = ApiConfigKit.getApiConfig();
			ApiConfigKit.putApiConfig(ac);
			ApiConfigKit.setThreadLocalAppId(ac.getAppId());
			String appId = ac.getAppId();
			String secret = ac.getAppSecret();
			SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(appId, secret, code);
			Integer errorCode=snsAccessToken.getErrorCode();
			if(errorCode!=null) {
				redirect("/vipCentent/oauth?type=toUserCar");
				return;
			}
			String openId = snsAccessToken.getOpenid();
			try {
				WeixinUser wxUser = WeixinUser.dao.getUserByOpenId(openId);
				//用户直接进没有注册
				if(wxUser==null) {
					redirect("/enroll/oauth");
					return;
				}
				Vip vip = Vip.dao.getVipByUserTel(wxUser.getTel(),shop_id);
				List<TimeCard> timecard=TimeCard.dao.timeCard(vip.getId());
				vip.setTimeCards(timecard);
				List<ValueCard> valueCard=ValueCard.dao.valueCard(vip.getId());
				vip.setValueCards(valueCard);
				setAttr("vip", vip);
				render("carBox.jsp");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 *******************************************
	 * 项目名称:weixin_meifa   
	 * 方法名称:用户信息页面
	 * 创建人：yanglong
	 * 创建时间：Dec 15, 2018 1:54:24 PM   
	 * @version
	 *******************************************
	 */
	public void UserInfo() {
		int vipId = getParaToInt("vipId");
		Vip vip =Vip.dao.findById(vipId);
		vip.setShop(Shop.dao.findById(vip.getShopId()));
		vip.setUser(WeixinUser.dao.getUserByvipId(vip.getId()));
		setAttr("vip", vip);
		render("userInfo.jsp");
	}

	/**
	 *******************************************
	 * 项目名称:weixin_meifa   
	 * 方法名称:到修改VIP页面
	 * 创建人：yanglong
	 * 创建时间：Dec 15, 2018 1:54:38 PM   
	 * @version
	 *******************************************
	 */
	public void updateUser() {
		int vipId = getParaToInt("vipId");
		Vip vip =Vip.dao.findById(vipId);
		WeixinUser user = WeixinUser.dao.getUserByvipId(vip.getId());
		vip.setUser(user);
		Map<String, Object> objMap=ShakeUtils.Shake(getRequest());
		setAttr("vip", vip);
		setAttr("objMap", objMap);
		render("updateUser.jsp");
	}
	/**
	 *******************************************
	 * 项目名称:weixin_meifa   
	 * 方法名称:修改VIP信息AJAX
	 * 创建人：yanglong
	 * 创建时间：Dec 18, 2018 3:29:12 PM   
	 * @version
	 *******************************************
	 */
	public void updateUserAjax() {
		String name=getPara("name");
		int age = getParaToInt("age");
		int vipId=getParaToInt("vipId");
		int sex=getParaToInt("sex");
		Vip vip =Vip.dao.findById(vipId);
		vip.setName(name);
		vip.setAge(age);
		vip.setSex(sex);
		if(vip.update()) {
			renderJson(vip.getId());
		}
	}



	/**
	 *******************************************
	 * 项目名称:weixin_meifa   
	 * 方法名称:到创建用户页面
	 * 创建人：yanglong
	 * 创建时间：Dec 18, 2018 2:54:01 PM   
	 * @version
	 *******************************************
	 */
	public void tocreateUser() {
		String openId = getPara("openId");
		WeixinUser user = WeixinUser.dao.getUserByOpenId(openId);
		Map<String, Object> objMap=ShakeUtils.Shake(getRequest());
		setAttr("objMap", objMap);
		if(user.getVipId()==null) {
			setAttr("user", user);
			render("createUser.jsp");
		}else {
			redirect("/vipCentent/updateUser?vipId="+user.getVipId());
			return;
		}
	}

	/**
	 *******************************************
	 * 项目名称:weixin_meifa   
	 * 方法名称:添加VIP的AJAX
	 * 创建人：yanglong
	 * 创建时间：Dec 18, 2018 3:27:09 PM   
	 * @version
	 *******************************************
	 */
	public void createUserAjax() {
		String name=getPara("name");
		int age = getParaToInt("age");
		int sex=getParaToInt("sex");
		String openId=getPara("openId");
		WeixinUser user = WeixinUser.dao.getUserByOpenId(openId);
		Vip vip = Vip.dao.getVipByUserTel(user.getTel(),shop_id);
		if(vip==null) {
			vip=new Vip();
			vip.setName(name);
			vip.setSex(sex);
			vip.setAge(age);
			vip.save();
			user.setVipId(vip.getId());
			renderJson(vip.getId());

		}else {
			vip.setName(name);
			vip.setSex(sex);
			vip.setAge(age);
			vip.update();
			user.setVipId(vip.getId());
			renderJson(vip.getId());
		}
	}

	/**
	 *******************************************
	 * 项目名称:weixin_meifa   
	 * 方法名称:通过serverId从微信公众平台临时素材库下载图片素材并更新用户头像
	 * 创建人：yanglong
	 * 创建时间：Dec 18, 2018 3:29:47 PM   
	 * @version
	 *******************************************
	 */
	@Before(Tx.class)
	public void downLodeImage() {
		String[] mediaId =getParaValues("serverId");
		String vipid = getPara("vipId");
		String url = "http://www.meifaguanli.com/weixin/";
		ApiConfigKit.putApiConfig(ApiConfigKit.getApiConfig());
		ApiConfigKit.setThreadLocalAppId("wxf1dced1caa5991d8");
		if(mediaId!=null&&mediaId.length>0) {
			for (int i = 0; i < mediaId.length; i++) {
				MediaFile mediaFile = MediaApi.getMedia(mediaId[i]);
				if(mediaFile!=null) {
					String path = "userImg";
					String fileDir = getRequest().getSession().getServletContext().getRealPath("").replaceAll("\\\\", "/")+path; 
					String imageName = IdGenerateTool.generateId()+"."+mediaFile.getSuffix();
					File f = new File(fileDir);
					// 创建文件夹
					if (!f.exists()) {
						f.mkdirs();
					}
					f = new File(fileDir+"/"+imageName);
					if (!f.exists()) {
						try {
							f.createNewFile();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					BufferedInputStream in  = mediaFile.getFileStream();
					int x;
					try {
						BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileDir+"/"+imageName));
						while((x=in.read())!=-1){
							out.write(x);
						}
						out.flush();
						out.close();
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					Vip vip = Vip.dao.findById(vipid);
					vip.setImgPath(url+path+"/"+imageName);
					vip.update();
				}else {
					System.out.println(vipid+"【"+i+"】：获取临时素材失败，mediaId："+mediaId[i]);
				}
			}
		}else {
			System.out.println(vipid+"：没有图片");
		}
		renderText("success");
	}


	public void cardBox() {
		Vip vip = Vip.dao.getVipByUserTel("18919986087",shop_id);
		List<TimeCard> timecard=TimeCard.dao.timeCard(vip.getId());
		vip.setTimeCards(timecard);
		List<ValueCard> valueCard=ValueCard.dao.valueCard(vip.getId());
		vip.setValueCards(valueCard);
		setAttr("vip", vip);
		render("carBox.jsp");
	}
}
